import { createApp } from 'vue'
import App from '@/App.vue'
import globalComponent from '@/components/index'
// svg插件需要配置代码
import 'virtual:svg-icons-register'
// 全局样式
import '@/styles/index.scss'
// 路由
import { constantRoute } from '@/router/routes'
import { createRouter, createWebHistory } from 'vue-router'
// 仓库
import pinia from './store'
import useUserInfoStore from '@/store/modules/userInfo'
//  配置qiankun
import {renderWithQiankun, qiankunWindow} from "vite-plugin-qiankun/dist/helper";
let app :any;
function render(props: any = {}) {
  const {container, routerBase } = props;
  // console.log("子应用渲染", props);
  
  app = createApp(App);  
  // 路由实例需要创建生成不能用一个实例
  const router = createRouter({
    routes: constantRoute,
    history: createWebHistory(routerBase), // routerBase基路径需要跟主应用activeRule保持一致
  })
  app.use(router);
  app.use(globalComponent)
  app.use(pinia)
  app?.mount(container ? container.querySelector('#app') : document.getElementById('app'));
}

renderWithQiankun({
  async mount(props) {
    render(props);
    // ==========划重点==========
    // 获取主应用传递的用户信息
    await props.onGlobalStateChange((state: any) => {
      const userInfoStore = useUserInfoStore()
      // console.log("子应用接收的参数", state);
      // 如果用户信息发生改变，则更新用户信息
      if(userInfoStore.userInfo.username !== state.username) {
        userInfoStore.setInfo({
          userInfo: state
        })
      }
    }, true);
  },
  bootstrap() {
    // console.log('vite被加载了');
    
  },
  update() {
    // console.log('vite更新了');
  },
  unmount() {
    // console.log('vite被卸载了')
    app.unmount();
    app._container.innerHTML = "";
    app = null;
  }
});
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  console.log("并不是qiankun渲染");
  // 单独运行需要获取用户信息
  render();
}
